<template>
  <div style="display: flex;margin: 20px auto;justify-content: center">
    <div>
      <el-page-header @back="$router.go(-1)">
      </el-page-header>
    </div>
    <div>
      <el-button @click="toExport()" type="primary" style="margin-left: 1000px;">导出评价</el-button>
      <el-scrollbar style="height: 100vh;width: 1100px; margin: 0 auto">
        <el-card class="comment-item" v-for="comment in comments" :key="comment.review_id">
          <div class="comment-header">
            <div
              style="height: 50px; width: 50px; border-radius: 50%; border: 2px solid black; background-color: transparent; overflow: hidden;">
              <img :src="comment.userFace" style="width: 100%; height: 100%; ">
            </div>
            <span class="user-name">{{ comment.realname }}</span>
            <el-rate v-model="comment.rating_average" disabled show-score text-color="#ff9900"
              score-template="{value}" />
            <el-tag style="margin-left: 700px;color: blanchedalmond; background-color: plum; font-size: 16px;">{{
              comment.tag }}</el-tag>
          </div>
          <div class="comment-body" style="display: flex; justify-content: space-between">
            <div>{{ comment.comment }}</div>
            <div>
              <el-button type="text" @click="toggleReply(comment)">回复</el-button>
            </div>
          </div>
          <div class="comment-footer">
            <span>{{ Number(comment.created) | fmtDate }}</span>
          </div>
          <div v-if="comment.editing" class="reply-form">
            <el-form :model="comment" :rules="rules" ref="commentForm">
              <el-form-item label="回复内容" prop="replyContent">
                <el-input v-model="comment.replyContent" placeholder="请输入回复内容" maxlength="30"
                  show-word-limit></el-input>
              </el-form-item>
            </el-form>
            <el-button style="margin-top: 10px;" type="primary" @click="submitReply(comment)">提交回复</el-button>
          </div>
          <div v-if="comment.replies && comment.replies.length > 0" class="replies">
            <div v-for="  reply in comment.replies" :key="comment.replies.id" class="reply"
              style="display: flex; align-items: center; margin-top: 20px;">
              <div
                style="height: 40px;  width: 40px; border-radius: 50%; background-color: #ccc; color: #fff; text-align: center; line-height: 40px;">
                <img :src="reply.userFace" alt="" style="width: 100%;height: 100%;">
              </div>
              <div
                style="width: 100%; display: flex; justify-content: space-between; align-items: center; font-size: 14px;">
                <div>
                  <div style="font-size:13px; font-family: monospace; margin-left: 10px;">{{ reply.realname }}</div>
                  <div style="margin: 10px 0 0 10px;">{{ reply.content }}</div>
                </div>
                <div>{{ Number(comment.created) | fmtDate }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-scrollbar>
    </div>

  </div>
</template>

<script>
import { get, getBlob, post } from '@/utils/request'
import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      'userId',
    ])
  },
  data() {
    return {
      comments: [],
      replies: {},
      rules: {
        replyContent: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 1, max: 10, message: '回复内容长度在 1 到 30 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    async submitReply(comment) {
      // 检查回复内容是否为空
      if (!comment.replyContent.trim()) {
        // 如果为空，显示错误提示
        this.$message.error('回复内容不能为空');
        return; // 终止方法执行
      }
      // 直接在对象字面量中赋值
      this.replies = {
        parent_id: comment.review_id,
        user_id: this.userId,
        content: comment.replyContent,
      };
      console.log(this.replies);
      let res = await post('/review/addReply', this.replies)
      comment.replyContent = ''; // 清空回复内容
      comment.editing = false; // 关闭编辑状态
      this.$message.success(res.message);
      this.getComments()
    },
    toggleReply(comment) {
      comment.editing = !comment.editing
      comment.replyContent = ''
    },
    async toExport() {
      // 从当前路由中获取课程ID和课程名
      const { id, name } = this.$route.query;
      console.log(id, name);

      await getBlob('/review/exportReviews', {
        courseId: id,
        courseName: name,
      }).then(res => {
        console.log(res);
        // 创建 Blob 对象
        const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        console.log(blob);
        // 创建一个 URL 以指向 Blob 对象
        const url = window.URL.createObjectURL(blob);
        // 创建下载链接
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `${name}_reviews.xlsx`); // 使用课程名作为文件名的一部分
        document.body.appendChild(link);
        // 自动点击下载链接以触发下载
        link.click();
        // 清理临时元素和对象 URL
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      })
        .catch(error => {
          // 处理错误并输出到控制台
          console.error('导出失败:', error);
        });
    },

    async getComments() {
      let res = await get('review/reviewsByStatus', { courseId: this.$route.query.id })
      // console.log(res);
      this.comments = res.data.map(comment => ({
        ...comment,
        editing: false // 初始化 editing 属性
      }));

    }
  },
  created() {
    this.getComments()
  }
};
</script>

<style>
.comment-item {
  margin-bottom: 20px;
  max-width: 1100px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-name {
  margin-left: 10px;
  margin-right: 20px;
}

.comment-body {
  margin-bottom: 10px;
}

.comment-footer {
  text-align: right;
}


.reply-form {
  margin-top: 10px;
}

.reply-form /deep/ .el-input__inner {
  border: none;
  border-bottom: 1px solid #dcdfe6;
  border-radius: 0;
}

.reply-form /deep/ .el-button {
  margin-left: 10px;
}

.replies {
  margin-top: 10px;
  padding-left: 20px;
  border-left: 2px solid #ccc;
}

.reply-content {
  margin-left: 10px;
  text-align: center;
}
</style>